package libgin

import (
	"net/http"
	"regexp"

	"github.com/gin-gonic/gin"
)

var (
	Return = new(ReturnJSON)
)

type ReturnJSON struct {
	Code       int         `json:"code"`
	StatusText string      `json:"status_text"`
	Message    interface{} `json:"message,omitempty"`
}

func (r *ReturnJSON) Set(code int, msg interface{}) *ReturnJSON {
	r.Code = code
	r.StatusText = http.StatusText(code)
	r.Message = msg
	return r
}

func (r *ReturnJSON) Ok(i interface{}) *ReturnJSON {
	return r.Set(http.StatusOK, i)
}

func (r *ReturnJSON) GinSet(c *gin.Context, code int, msg interface{}) {
	c.JSON(code, r.Set(code, msg))
}

func (r *ReturnJSON) GinOK(c *gin.Context, msg interface{}) {
	c.JSON(http.StatusOK, r.Set(http.StatusOK, msg))
}

func (r *ReturnJSON) MiddlewareErr(c *gin.Context) {
	c.Next()
	if len(c.Errors) != 0 {
		var code = http.StatusInternalServerError
		msg := c.Errors.ByType(gin.ErrorTypeAny).Last().Error()
		//验证错误是否包含中文
		if ok, _ := regexp.MatchString(".*[\u4e00-\u9fa5]+.*", msg); ok {
			code = http.StatusBadRequest
		}
		c.Abort()
		Return.GinSet(c, code, msg)
	}
}

func (r *ReturnJSON) Scheme(ctx *gin.Context) string {
	if scheme := ctx.GetHeader(HeaderXForwardedProto); scheme != "" {
		return scheme
	}
	if ctx.Request.URL.Scheme != "" {
		return ctx.Request.URL.Scheme
	}
	if ctx.Request.TLS == nil {
		return "http"
	}
	return "https"
}

// Site returns base site url as `scheme://domain:port` type.
func (r *ReturnJSON) Site(ctx *gin.Context) string {
	return r.Scheme(ctx) + "://" + ctx.Request.Host
}

type WarpGinHandler func(*gin.Context) (err error)

func (r *ReturnJSON) WarpHandler(fn WarpGinHandler) gin.HandlerFunc {
	return func(c *gin.Context) {
		var err error
		if err = fn(c); err != nil {
			c.Abort()
			_ = c.Error(err)
		}
	}
}
